package com.tinghua.mqTest.deal;

import com.rabbitmq.client.*;
import com.tinghua.mqTest.utils.ConnectionMQ;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列案例
 * 这里设置了超时时间、队列最大长度、拒绝接收的方式来测试死信队列的使用
 * 当触碰上面的底线后，将转发至死信队列
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        Channel channel = ConnectionMQ.utilConnectionMQ();
        channel.exchangeDeclare("myExchange", BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare("dealExchange", BuiltinExchangeType.DIRECT);
        //配置要绑定的死信队列
        Map<String, Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", "dealExchange");
        map.put("x-dead-letter-routing-key", "keyq2");
        //设置队列最大长度，超过该长度的数据也会被放到死信队列中处理
        map.put("x-max-length", 6);
        //由正常队列绑定死信队列
        channel.queueDeclare("Q1", false, false, false, map);
        channel.queueDeclare("Q2", false, false, false, null);
        channel.queueBind("Q1", "myExchange", "keyq1");
        channel.queueBind("Q2", "dealExchange", "keyq2");

        //队列Q1接收消息
        channel.basicConsume("Q1", false, (String consumerTag, Delivery message) -> {
            System.out.println("Q1处理消息... ");
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            if (msg.equals("err")) {
                //拒绝接收该消息
                System.out.println("消息 " + msg + " 已被拒绝");
                //第二个参数是指是否重新放回原队列，这里设置否，将会放到配置好的死信队列
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                //接收该消息
                System.out.println("消息 " + msg + " 已被接收");
                //第二个参数是指是否为批量应答
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        }, consumerTag -> {});
    }
}
